import React, { Component } from 'react';
import { Button, message } from 'antd';
import './header.css';
import { weatherRequest } from '../../api/index';

export default class header extends Component {
  constructor(props) {
    super(props);
    this.currentCity = '武汉';
    weatherRequest(this.currentCity).then(
      (success) => {
        this.setState(success);
      },
      (error) => {
        message.error('获取天气失败!');
      }
    );
  }

  state = {
    currentTime: null,
    weather: null,
    reporttime: null,
    temperature: null,
  };

  getTime = () => {
    var myDate = new Date();
    return (
      myDate.getFullYear() +
      '-' +
      (myDate.getMonth() + 1) +
      '-' +
      myDate.getDate() +
      ' ' +
      myDate.getHours() +
      ':' +
      myDate.getMinutes() +
      ':' +
      myDate.getSeconds()
    );
  };

  setTime = () => {
    this.timer = setInterval(() => {
      const currentTime = this.getTime();
      this.setState({ currentTime: currentTime });
    }, 1000);
  };

  componentDidMount() {
    this.setTime();
  }

  componentWillUnmount() {
    clearInterval(this.timer);
  }

  render() {
    return (
      <div className="header-container">
        <div className="header-welcome">Hello, {this.props.user.username}!</div>
        <Button
          type="primary"
          htmlType="submit"
          size="small"
          className="header-button"
          onClick={this.props.logOut}
        >
          选择登出
        </Button>
        <Button
          type="primary"
          size="small"
          htmlType="submit"
          className="header-button"
          onClick={this.props.logOutAndClear}
        >
          登出并清除数据
        </Button>
        <div className="header-text">
          <div className="header-date">当前时间：{this.state.currentTime}</div>
          <div className="header-weather">
            当前天气：{this.state.weather}
            &nbsp; 当前温度：{this.state.temperature}°C &nbsp; 更新时间：
            {this.state.reporttime}
          </div>
        </div>
      </div>
    );
  }
}
